package com.heima.wemedia.filter;

import com.alibaba.fastjson.JSON;
import com.heima.wemedia.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @Description: 认证过滤器
 * @Version: V1.0
 */
@Component
@Slf4j
@Order(0) // 值越小越优先执行
public class AuthorizeFilter implements GlobalFilter {
  private static List<String> urlList = new ArrayList<>();
  // 初始化白名单 url路径
  static {
    urlList.add("/login/in");
    urlList.add("/v2/api-docs");
  }

  /**
   * 过滤方法
   * @param exchange 请求响应上下文
   * @param chain 过滤器链对象
   * @return
   */
  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpResponse response = exchange.getResponse();
    //1.获取请求路径
    ServerHttpRequest request = exchange.getRequest();
    String path = request.getURI().getPath();
    //2.判断路径是否属于白名单
    for (String allowUrl : urlList) {
      if (path.contains(allowUrl)) {
        //如果属于白名单路径，直接放行
        return chain.filter(exchange);
      }
    }
    //3.判断用户请求头中是否携带token
    String token = request.getHeaders().getFirst("token");
    if (StringUtils.isBlank(token)) {
      //如果未携带token，直接终止请求  返回401状态
//      response.setStatusCode(HttpStatus.UNAUTHORIZED);
//      return response.setComplete();
      return writeMessage(exchange,"未携带token");
    }
    //4。校验token是否有效
    try {
      //获取token的负载信息
      Claims claimsBody = AppJwtUtil.getClaimsBody(token);
      //-1：有效，0：有效，1：过期，2：过期
      int i = AppJwtUtil.verifyToken(claimsBody);
      if(i<1){
        //4.1有效  获取token中存储的userId 将用户id路由给其他客户端
        Object id = claimsBody.get("id");
        //将userId 设置到请求头中，用于路由给其他微服务
        request.mutate().header("userId",String.valueOf(id));
        return chain.filter(exchange);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
         //4.2无效  直接终止请求 返回401状态
    return writeMessage(exchange,"解析失败");
  }
  /**
     * 返回错误提示信息
     * @return
     */
  private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
    Map<String, Object> map = new HashMap<>();
    map.put("code", HttpStatus.UNAUTHORIZED.value());
    map.put("errorMessage", message);
    //获取响应对象
    ServerHttpResponse response = exchange.getResponse();
    //设置状态码
    response.setStatusCode(HttpStatus.UNAUTHORIZED);
    //response.setStatusCode(HttpStatus.OK);
    //设置返回类型
    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    //设置返回数据
    DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
    //响应数据回浏览器
    return response.writeWith(Flux.just(buffer));
  }
}